//
//  QToast.m
//  quinn
//
//  Created by bug neo on 08/12/2020.
//  Copyright © 2020 neobug. All rights reserved.
//

#import "TSToast.h"
#import <Masonry/Masonry.h>

@interface TSToastView : UIView

@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) UILabel *toastLabel;
@property (nonatomic, copy) NSString *str;

- (void)show;
@end

static TSToastView *toastV = nil;

@implementation TSToastView

- (instancetype)init {
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self addSubview:self.backView];
        [self addSubview:self.toastLabel];
        [self.toastLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.mas_centerX);
            make.centerY.equalTo(self.mas_centerY);
            make.width.mas_lessThanOrEqualTo([UIScreen mainScreen].bounds.size.width-100);
//            make.height.mas_equalTo(100);
//            make.width.mas_equalTo(100);
        }];
        [self.backView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.toastLabel.mas_top).offset(-10);
            make.left.equalTo(self.toastLabel.mas_left).offset(-10);
            make.bottom.equalTo(self.toastLabel.mas_bottom).offset(10);
            make.right.equalTo(self.toastLabel.mas_right).offset(10);
        }];
    }
    return self;
}

- (void)show {
    
    [[UIApplication sharedApplication].keyWindow addSubview:toastV];
//    toastV.frame = CGRectMake(0, 0, 100, 100);
    toastV.center = [UIApplication sharedApplication].keyWindow.center;
    toastV.toastLabel.text = self.str;
    NSLog(@"%@",self.str);
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [toastV removeFromSuperview];
        toastV = nil;
    });
}

- (UIView *)backView {
    if (!_backView ) {
        _backView = [UIView new];
        _backView.backgroundColor = [UIColor colorWithRed:21/255.0 green:21/255.0 blue:21/255.0 alpha:0.6];
        _backView.layer.cornerRadius = 5;
        _backView.layer.masksToBounds = YES;
    }
    return _backView;
}

- (UILabel *)toastLabel {
    if (!_toastLabel ) {
        _toastLabel = [UILabel new];
        _toastLabel.textColor = [UIColor whiteColor];
        _toastLabel.font = [UIFont systemFontOfSize:15];
        _toastLabel.textAlignment = NSTextAlignmentCenter;
        _toastLabel.numberOfLines = 0;
    }
    return _toastLabel;
}

@end




@implementation TSToast
+ (void)toast:(NSString *)str {
    if (!toastV) {
        toastV = [[TSToastView alloc] init];
        if (str.length) {
            toastV.str = str;
            [toastV show];            
        }
    }
}

@end



